package com.heima.article.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.ArticleService;
import com.heima.common.contans.article.ArticleConstans;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper , ApArticle> implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Value("${fdfs.url}")
    private String fdfsUrl;

    @Override
    public ResponseResult load(ArticleHomeDto dto, Short loadtype) {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页校验
        Integer size = dto.getSize();
        if (size == null || size == 0){
            size = 10;
        }
        size = Math.min(size , 50);
        //频道校验
        dto.setSize(size);
        if (StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstans.DEFAULT_TAG);
        }
        //类型惨数校验
        if (!loadtype.equals(ArticleConstans.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstans.LOADTYPE_LOAD_NEW)){
            loadtype = ArticleConstans.LOADTYPE_LOAD_MORE;
        }
        //时间校验
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());

        List<ApArticle> apArticles = articleMapper.loadArticleList(dto, loadtype);
        ResponseResult result = ResponseResult.okResult(apArticles);
        result.setHost(fdfsUrl);
        return result;
    }
}
